package com.product.system.imageCline.strategy;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.product.system.controller.ImageController.IMAGE_LAGNGUAGE_PATH;

public class IdCardStrategy implements ParsePicStrategy {

    private String file;

    /**
     * 身份证识别
     * @param file
     */
    public IdCardStrategy(String file){
        this.file=file;
    }

    @Override
    public Map<String,String> parsePicSave(String file) {
        String url = file;
        try {
//            URL url = new URL(file);
//            System.out.println(url+"ppppppppppppppppppppp");
//            BufferedImage image = ImageIO.read(url);
//            System.out.println(image);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            byte[] imageData = EntityUtils.toByteArray(entity);
            //将图片数据保存为临时文件
            File image = File.createTempFile("tempImage", ".jpg");
            try (OutputStream os = new FileOutputStream(image)){
                os.write(imageData);
            }
            //使用Tesseract进行OCR识别
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath(IMAGE_LAGNGUAGE_PATH);
            tesseract.setLanguage("chi_sim");
            String result = tesseract.doOCR(image).replace("\n", "").replace(" ", "");
            System.out.println(result);
            int startIndex = result.indexOf("姓名") + "姓名".length();
            int endIndex = result.indexOf("性");
            String name = result.substring(startIndex, endIndex).trim();
            System.out.println("提取的姓名："+name);
            response.close();
            httpClient.close();
            HashMap<String, String> map = new HashMap<>();
            map.put("name",name);
            return map;
        }catch (IOException | TesseractException e){
            e.printStackTrace();
            return null;
        }
    }
}
